03. Spring Boot Exception - SimpleMappingExceptionResolver
035ND C01 L04 A06 SIMPLE MAPPING RESOLVER
00:00
00:00
Instructions
Let’s make our GloablExceptionHandler as bak first, so that we can keep our code. Rename GloablExceptionHandler.java to GlobalExceptionHandler.java.bak
Create a MySimpleMappingExceptionResolver class under exceptions directory.
@Configuration
public class MySimpleMappingExceptionResolver {
@Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties mapping = new Properties();
mapping.put("java.lang.ArithmeticException", "mathError"); //key=exception full name. value, view name
mapping.put("java.lang.NullPointerException", "nullPointerError");
resolver.setExceptionMappings(mapping);
return resolver;
}
}
If you refresh the page, you can see error is handled.
Demo
035ND C01 L04 A07 HANDLER EXCEPTION RESOLVER EXAMPLE
00:00
00:00
Let’s rename MySimpleMappingExceptionResolver.java to MySimpleMappingExceptionResolver.java.bak
Create MyHandlerExceptionResolver class under exceptions directory.
public class MyHandlerExceptionResolver implements HandlerExceptionResolver{
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse, @Nullable Object o, Exception e) {
ModelAndView mv = new ModelAndView();
if (e instanceof ArithmeticException) {
mv.setViewName("mathError");
}
if (e instanceof NullPointerException) {
mv.setViewName("nullPointerError");
}
mv.addObject("exception", e.toString());
return mv;
}
}